package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ImgsService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.Imgs;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.businessInspect.ImgsUpdate;
import com.ktwlsoft.archivemanage.service.img.FileStorageService;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.FileUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 图片上传
 *
 * @author zhuhe on 2019/10/30 11:39
 * @version 1.0
 */
@Component
public class ImgUploadService {

    /**通用图片*/
    private static ImgsService imgsService;

    /**图片上传*/
    private static FileStorageService fileStorageService;

    /**通用图片*/
    private final ImgsService i_imgsService;

    /**图片上传*/
    private final FileStorageService i_fileStorageService;

    public ImgUploadService(ImgsService imgsService, FileStorageService fileStorageService) {
        i_imgsService = imgsService;
        i_fileStorageService = fileStorageService;
    }

    @PostConstruct
    public void init(){
        imgsService = this.i_imgsService;
        fileStorageService = this.i_fileStorageService;
    }

    /**
     * 图片上传 on 2019/7/17 14:52
     *
     * @param files 文件集合
     * @param businessId 业务id
     * @param businessType 业务类型
     * @return ResponseEntity<?>
     */
    public static List<Imgs> imgUpload(List<MultipartFile> files, String businessId, String businessType){
        if (files.size() <= 0) {
            return null;
        }
        if (businessId == null || "".equals(businessId.trim())) {
            return null;
        }
        if(businessType == null || "".equals(businessType.trim())){
            return null;
        }
        List<Imgs> arrayList=null;
        //查询是否有过往数据
        Imgs img = new Imgs();
        img.setBusinessId(Long.parseLong(businessId));
        img.setBusinessType(businessType);
        List<Imgs> fileList = imgsService.getByBusinessIdAndBusinessType(img);
        String path = "";
        if (fileList != null && fileList.size() > 0) {
            if (fileList.get(0).getUrl().length() > 0 && fileList.get(0).getUrl().contains("\\")) {
                path = fileList.get(0).getUrl().substring(0, fileList.get(0).getUrl().lastIndexOf("\\"));
            } else {
                path = UUID.randomUUID().toString().replace("-", "") + File.separator + "TY";
            }
//            arrayList =updateImagesData(new String[]{businessId,businessType,path},files,((Imgs)fileList.get(0)).getId());
        } else {
            path = UUID.randomUUID().toString().replace("-", "") + File.separator + "TY";
//            arrayList =addImagesData(new String[]{businessId,businessType,path},files);
        }
        arrayList =addImagesData(new String[]{businessId,businessType,path},files);
        return arrayList;
    }

    /**
     * 新增上传图片
     * @param datas 业务编号、业务类型和路径
     * @param files 图片列表
     * @return List<Imgs>
     */
    private static List<Imgs> addImagesData(String[] datas,List<MultipartFile> files){
        List<Imgs> arrayList = Lists.newArrayList();
        for (MultipartFile value : files) {
            String fileName = fileStorageService.storeFile(value, datas[2]);
            Imgs imgs=prepareImagesData(new String[]{datas[0],datas[1],datas[2],fileName},value,true,null);
            try {
                imgsService.insert(imgs);
            } catch (Exception e) {
                e.printStackTrace();
            }
            arrayList.add(imgs);
        }
        return arrayList;
    }

    /**
     * 更新上传图片
     * @param datas 业务编号、业务类型和路径
     * @param files 图片列表
     * @param id 图片编号
     * @return List<Imgs>
     */
    private static List<Imgs> updateImagesData(String[] datas,List<MultipartFile> files,Long id){
        List<Imgs> arrayList = Lists.newArrayList();
        for (MultipartFile value : files) {
            String fileName = fileStorageService.storeFile(value, datas[2]);
            Imgs imgs=prepareImagesData(new String[]{datas[0],datas[1],datas[2],fileName},value,false,id);
            // 新增数据到数据库
            try {
                imgsService.updateImagesData(imgs);
            } catch (Exception e) {
                e.printStackTrace();
            }
            arrayList.add(imgs);
        }
        return arrayList;
    }

    /**
     * 根据路径删除服务器上已上传的图片
     * @param paths 路径列表
     */
    public static void deleteExistedFiles(List<String> paths){
        for(String path:paths){
            FileUtils.deleteFile(path);
        }
    }

    /**
     * 准备图片数据
     * @param datas 业务编号、业务类型和路径
     * @param value 文件对象
     * @param addflag 新增标识
     * @param id 图片编号
     * @return Imgs
     */
    private static Imgs prepareImagesData(String[] datas,MultipartFile value,boolean addflag,Long id){
        Imgs imgs = new Imgs();
        if(addflag){
            //id
            imgs.setId(SnowFlake.getNextId());
            //创建时间
            imgs.setCreatedAt(new Date());
        }else {
            imgs.setId(id);
        }
        //业务id
        imgs.setBusinessId(Long.parseLong(datas[0]));
        //业务类型
        imgs.setBusinessType(datas[1]);
        //相对地址
        imgs.setUrl(datas[2] + File.separator + datas[3]);
        //名称
        imgs.setFileName(datas[3]);
        //后缀
        String[] strArr = datas[3].split("\\.");
        imgs.setSuffix(strArr[1]);
        //大小
        imgs.setSize(value.getSize());
        //创建人
        imgs.setCreator(null);
        //创建人id
        imgs.setCreatorId(null);
        //更新时间
        imgs.setUpdateAt(new Date());

        return imgs;
    }

    /**
     * 获取图片在服务器上的路径
     * @param url
     * @return String
     */
    public static String getImagePath(String url){
        return fileStorageService.getStrPath(url);
    }

    /**
     * 图片上传 on 2019/7/17 14:52 zhuhe
     *
     * @param files 文件集合
     * @param businessId 业务id
     * @param businessType 业务类型
     * @return ResponseEntity<?>
     */
    public static List<Imgs> imgUploads(List<MultipartFile> files, String businessId, String businessType){
        if (files.size() <= 0) {
            return null;
        }
        if (businessId == null || "".equals(businessId.trim())) {
            return null;
        }
        if(businessType == null || "".equals(businessType.trim())){
            return null;
        }
        String s = businessId + "_" + businessType + File.separator + "TY";
        List<Imgs> arrayList = Lists.newArrayList();
        Account account = UserPrincipal.getCurrentUser();
        for (MultipartFile value : files) {
            String fileName = StringUtils.cleanPath(value.getOriginalFilename());
            String newFileName = String.valueOf(SnowFlake.getNextId()) + fileName.substring(fileName.lastIndexOf("."),fileName.length());
            fileStorageService.storeFile(value, s,newFileName);
            // 新增数据到数据库
            Imgs imgs = new Imgs();
            //id
            imgs.setId(SnowFlake.getNextId());
            //业务id
            imgs.setBusinessId(Long.parseLong(businessId));
            //业务类型
            imgs.setBusinessType(businessType);
            //相对地址
            imgs.setUrl(s + File.separator + newFileName);
            //名称
            imgs.setFileName(fileName);
            //后缀
            String[] strArr = fileName.split("\\.");
            imgs.setSuffix(strArr[strArr.length -1]);
            //大小
            imgs.setSize(value.getSize());
            //创建人
            imgs.setCreator(account != null?account.getUserName():null);
            //创建人id
            imgs.setCreatorId(account != null?account.getId():null);
            //创建时间
            imgs.setCreatedAt(new Date());
            //更新时间
            imgs.setUpdateAt(new Date());
            try {
                imgsService.insert(imgs);
            } catch (Exception e) {
                e.printStackTrace();
                return arrayList;
            }
            arrayList.add(imgs);
        }
        return arrayList;
    }

    /**
     * 图片上传 on 2019/7/17 14:52 zhuhe
     *
     * @param files 文件集合
     * @param businessId 业务id
     * @param businessType 业务类型
     * @param name 文件名
     * @return ResponseEntity<?>
     */
    public static List<Imgs> imgUploads(List<MultipartFile> files, String businessId, String businessType,String name){
        if (businessId == null || "".equals(businessId.trim())) {
            return null;
        }
        if(businessType == null || "".equals(businessType.trim())){
            return null;
        }
        String s = businessId + "_" + businessType + File.separator + "TY";
        List<Imgs> arrayList = Lists.newArrayList();
        Account account = UserPrincipal.getCurrentUser();
        for (MultipartFile value : files) {
            String newFileName = String.valueOf(SnowFlake.getNextId()) + name.substring(name.lastIndexOf("."),name.length());
            fileStorageService.storeFile(value, s,newFileName);
            // 新增数据到数据库
            Imgs imgs = new Imgs();
            //id
            imgs.setId(SnowFlake.getNextId());
            //业务id
            imgs.setBusinessId(Long.parseLong(businessId));
            //业务类型
            imgs.setBusinessType(businessType);
            //相对地址
            imgs.setUrl(s + File.separator + newFileName);
            //名称
            imgs.setFileName(name);
            //后缀
            String[] strArr = name.split("\\.");
            imgs.setSuffix(strArr[strArr.length -1]);
            //大小
            imgs.setSize(value.getSize());
            //创建人
            imgs.setCreator(account != null?account.getUserName():null);
            //创建人id
            imgs.setCreatorId(account != null?account.getId():null);
            //创建时间
            imgs.setCreatedAt(new Date());
            //更新时间
            imgs.setUpdateAt(new Date());
            try {
                imgsService.insert(imgs);
            } catch (Exception e) {
                e.printStackTrace();
                return arrayList;
            }
            arrayList.add(imgs);
        }
        return arrayList;
    }

    /**
     * 图片上传 on 2019/7/17 14:52 zhuhe
     *
     * @param files 文件集合
     * @return ResponseEntity<?>
     */
    public static List<Imgs> imgUploadsNoData(List<MultipartFile> files){
        if (files.size() <= 0) {
            return null;
        }
        String s = UUID.randomUUID().toString().replace("-", "") + File.separator + "TY";
        List<Imgs> arrayList = Lists.newArrayList();
        for (MultipartFile value : files) {
            String fileName = fileStorageService.storeFile(value, s);
            Imgs imgs = new Imgs();
            //相对地址
            imgs.setUrl(s + File.separator + fileName);
            //名称
            imgs.setFileName(StringUtils.cleanPath(value.getOriginalFilename()));
            //后缀
            String[] strArr = fileName.split("\\.");
            imgs.setSuffix(strArr[strArr.length -1]);
            //大小
            imgs.setSize(value.getSize());
            arrayList.add(imgs);
        }
        return arrayList;
    }

    /**
     * 物理删除 on 2019/10/31 16:32 zhuhe
     *
     * @param id id
     * @return Result<?>
     */
    public static Result<?> deleteById(Long id){
        if(id == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id为空");
        }
        Imgs imgs = imgsService.getById(id);
        if(imgs == null){
            return Result.body(null,ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        try {
            imgsService.deleteById(id);
            //删除图片
            if(imgs.getUrl() != null) {
                FileUtils.deleteFile(fileStorageService.getStrPath(imgs.getUrl()));
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null,ResultType.DELETE_ERROR);
        }
        return Result.ok("");
    }

    /**
     * 物理删除 on 2019/10/31 16:32 zhuhe
     *
     * @param bId bId
     * @param bType bType
     * @return Result<?>
     */
    public static Result<?> deleteByBIdAndBType(Long bId,String bType){
        if(bId == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id为空");
        }
        if(bType == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id为空");
        }
        Imgs imgs = new Imgs();
        imgs.setBusinessId(bId);
        imgs.setBusinessType(bType);
        List<Imgs> imgss = imgsService.getByBusinessIdAndBusinessType(imgs);
        if(imgss == null || imgss.size() <= 0){
            return Result.body(null,ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        //删除图片
        List<Long> longs = Lists.newArrayList();
        for(Imgs imgs1:imgss){
            if(imgs1.getUrl() != null) {
                try {
                    FileUtils.deleteFile(fileStorageService.getStrPath(imgs1.getUrl()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            longs.add(imgs1.getId());
        }
        try {
            imgsService.deleteByIds(longs);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null,ResultType.DELETE_ERROR);
        }
        return Result.ok("");
    }

    /**
     * 处理图片 on 2019/11/13 10:18
     *
     * @param bId      bId
     * @param bType    bType
     * @param imgsList imgsList
     * @return Integer
     */
    public static Integer handleImg(Long bId, String bType, List<ImgsUpdate> imgsList) {
        if (imgsList == null || imgsList.size() <= 0) {
            return 0;
        }
        List<Imgs> saveImg = Lists.newArrayList();
        List<Imgs> deleteImg = Lists.newArrayList();
        for (ImgsUpdate imgsUpdate : imgsList) {
            Imgs imgs = new Imgs();
            BeanUtils.copyProperties(imgsUpdate, imgs);
            if (imgsUpdate.getType().equals(1)) {
                saveImg.add(imgs);
            } else if (imgsUpdate.getType().equals(2)) {
                deleteImg.add(imgs);
            }
        }
        if (saveImg.size() > 0) {
            imgsService.manySave(bId, bType, saveImg);
        }
        if (deleteImg.size() > 0) {
            for (Imgs imgs : deleteImg) {
                deleteById(imgs.getId());
            }
        }
        return 1;
    }

    public static int deleteByBusinessId(Long businessId) {
        Imgs imgs = new Imgs();
        imgs.setBusinessId(businessId);
        List<Imgs> imgss = imgsService.findList(imgs);
        if(imgss == null || imgss.size() <= 0){
            return 0;
        }
        //删除图片
        for(Imgs imgs1:imgss){
            if(imgs1.getUrl() != null) {
                try {
                    FileUtils.deleteFile(fileStorageService.getStrPath(imgs1.getUrl()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return imgsService.deleteImagesByBusinessId(businessId);
    }
}